import { dirname } from 'path';
import * as fs from "fs";
import * as path from "path";

let dir:string;
let file: string;

dir = "E:/TypeScript/jcre";
file = "E:/TypeScript/jcre/javacard/framework/javacard/debug.msk";

let data:Buffer = fs.readFileSync(file);


fs.writeFileSync("x.txt", "11223344", {flag:'a+'});
function enumDirFiles(dirname: string){
    let paths: string[];
    paths = fs.readdirSync(dirname);
    paths.forEach(element => {
        let nextpath:string = path.join(dirname, element);
        let fstat:fs.Stats = fs.statSync(nextpath);
        if(fstat.isDirectory()){
            enumDirFiles(nextpath);
        }
        else{
            let posmsk: number = nextpath.lastIndexOf(".");

            if(nextpath.substr(posmsk) == ".msk"){
                let pkgname: string;
                let pkgaid: string;
                let mskdata: Buffer;
                let jcadata: Buffer;
                let posdir: number = nextpath.lastIndexOf("\\");
                let curdir: string = nextpath.substring(0, posdir);
                let dirfile: string[] = fs.readdirSync(curdir);
                dirfile.forEach(element=>{
                    let posjca: number = element.lastIndexOf(".");
                    if(element.substr(posjca) == ".jca"){
                        console.log(path.join(curdir, element));
                        jcadata = fs.readFileSync(path.join(curdir, element));
                        let strjca: string = jcadata.toString();
                        let regstr = /\.package ([a-zA-Z0-9/]+) \{\s*.aid ([0-9A-Fx:]+);/;
                        let result = regstr.exec(jcadata.toString());
                        pkgname = result[1];
						pkgaid = result[2].replace(/:/g,"");
                        console.log(pkgname);
                        let aid:string[] = pkgaid.split("0x").slice(1);
                        let aid2:string = "";
                        console.log(aid);
                        aid.forEach((element, index)=>{
                            console.log(element);
                            if(element.length == 1)
                                element = "0"+element;
                            aid2 += element;
                        })
                        console.log(aid2);
                        console.log("end");
                        
                    }
                })
            }
            
            
        }
        
    });
}

//enumDirFiles(dir);
